package org.oncase.smcase.util;

import javax.persistence.PersistenceException;

import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

	private static final SessionFactory sessionFactory;
	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	private HibernateUtils() throws HibernateException, JDBCException {
	}

	public static Session currentSession() throws PersistenceException {
		Session s = (Session) session.get();

		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}

		return s;
	}

	public static void closeSession() throws HibernateException, JDBCException {
		Session s = (Session) session.get();
		session.set(null);

		if (s != null) {
			if (s.isOpen()) {
				s.flush();
				s.close();
			}
		} else {
			System.out.println("Hibernate session was inadvertently already closed.");
		}
	}

}